package com.airticketbooking.service.serviceImpl;

import com.airticketbooking.common.constant.StatusConstant;
import com.airticketbooking.common.domain.PageQuery;
import com.airticketbooking.common.utils.BeanUtils;
import com.airticketbooking.common.utils.UserContext;
import com.airticketbooking.dto.UserDTO;
import com.airticketbooking.po.User;
import com.airticketbooking.vo.UserPageVO;
import com.airticketbooking.mapper.UserMapper;
import com.airticketbooking.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;



@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {


	private final UserMapper userMapper;

	@Override
	public User getUserByUserName(String userName) {

		return userMapper.getUserByUserName(userName);

	}

	@Override
	@Transactional
	public void add(User user) {

		user.setCreateDate(LocalDateTime.now());
		user.setStatus(1);
		userMapper.add(user);
	}

	@Override
	@Transactional
	public void modify(UserDTO userDTO) {
		User user = new User();
		user.setUserId(UserContext.getUser().intValue());
		BeanUtils.copyProperties(userDTO, user);
		user.setUpdateDate(LocalDateTime.now());
		userMapper.update(user);
	}

	@Override
	public User getUserById(Integer userId) {

		return userMapper.getUserById(userId);
	}

	@Override
	public Page<UserPageVO> getUserByPage(PageQuery pageQuery) {

		PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());

		return userMapper.getUserByPage(pageQuery);
	}

	@Override
	@Transactional
	public void updatePsw(User user) {

		userMapper.update(user);

	}

	@Override
	@Transactional
	public void openOrBanUser(Integer userId) {

		User user = userMapper.getUserById(userId);

		if (user == null) {
			throw new IllegalArgumentException("用户不存在");
		}

		Integer newStatus = StatusConstant.ENABLE;

		if (user.getStatus() == StatusConstant.ENABLE) {

			newStatus = StatusConstant.DISABLE;
		} else if (user.getStatus() == StatusConstant.DISABLE) {
			newStatus = StatusConstant.ENABLE;
		}

		user.setStatus(newStatus);
		user.setUpdateDate(LocalDateTime.now());
		userMapper.update(user);

	}

	@Override
	@Transactional
	public void changePassword(String oldPassword, String newPassword, String rePassword) {

		if (!newPassword.equals(rePassword)) {
			throw new IllegalArgumentException("两次输入的密码不一致");
		}

		User user = userMapper.getUserById(UserContext.getUser().intValue());

		if (!user.getPassword().equals(oldPassword)) {
			throw new IllegalArgumentException("原密码错误");
		}

		user.setPassword(newPassword);
		user.setUpdateDate(LocalDateTime.now());

		userMapper.update(user);
	}
}
